package com.example.myapp

import android.animation.Animator
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.InputFilter
import android.text.Spanned
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.airbnb.lottie.LottieDrawable
import com.example.myapp.base.BaseActivity
import com.example.myapp.databinding.ActivityMainBinding
import com.example.myapp.router.PageRouter
import com.example.myapp.router.RouterKey
import com.example.myapp.router.RouterPath
import com.example.myapp.service.MyService
import com.idlefish.flutterboost.interfaces.IFlutterViewContainer
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.plugins.FlutterPlugin
import java.util.*
import java.util.regex.Pattern

class MainActivity : BaseActivity() {

   private var  mainActivityBinding:ActivityMainBinding?=null
    private val REQUEST_CODE_FLUTTER = 1001

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.e("tag","onCreate")

        mainActivityBinding= ActivityMainBinding.inflate(layoutInflater)
        setContentView(mainActivityBinding?.root)

        mainActivityBinding?.btnStartMain?.setOnClickListener {
            //启动 Flutter 页面
            PageRouter.openPageByUrl(this, RouterPath.Main.PAGE_MAIN)
            mainActivityBinding?.tvResultData?.text =""
        }

      mainActivityBinding?.btnStartHasResult?.setOnClickListener {
            //无传参启动 Flutter 页面，并接收 Flutter 页面回调数据
          Thread.sleep(20000)
            PageRouter.openPageByUrl(
                this,
                RouterPath.Test.PAGE_HAS_RESULT,
                requestCode = REQUEST_CODE_FLUTTER
            )
          mainActivityBinding?.tvResultData?.text =""
        }

       mainActivityBinding?.btnStartHasParams?.setOnClickListener {
            //传参启动 Flutter 页面
//            val params = mutableMapOf<String, Any>()
//            params.put(RouterKey.Test.HasParamsActivity.EXTRA_KEY_ID, 452713L)
//            params.put(RouterKey.Test.HasParamsActivity.EXTRA_KEY_GROUP, "小学生")
//            PageRouter.openPageByUrl(
//                this,
//                RouterPath.Test.PAGE_HAS_PARAMS,
//                requestParams = params
//            )
//           mainActivityBinding?.tvResultData?.text =" "
           val source = mainActivityBinding?.editText?.text.toString()
           judegeRegx(source)
        }
        var translationY=0f
        //手动设置maxLength为10
        val filters: Array<InputFilter> = arrayOf(MyLengthFilter(10,this))
        mainActivityBinding?.editText?.filters = filters
        mainActivityBinding?.btnSend?.setOnClickListener{

//            Log.e("tag","点击事件了按钮")
//            translationY += 50f
//            mainActivityBinding?.btnSend?.translationY =translationY
            startActivity(Intent(this@MainActivity,SecondActivity::class.java))
           val myService = MyService();
            myService.stopSelf()
        }

//        mainActivityBinding?.animationView?.loop(true)
//        mainActivityBinding?.animationView?.repeatMode = LottieDrawable.RESTART
//        mainActivityBinding?.animationView?.setAnimationFromUrl("https://cqz-1256838880.cos.ap-shanghai.myqcloud.com/bird1.json")

//        mainActivityBinding?.animationView?.addAnimatorListener(object :Animator.AnimatorListener{
//            override fun onAnimationStart(animation: Animator?) {
//                Log.e("tag","onAnimationStart")
//            }
//
//            override fun onAnimationEnd(animation: Animator?) {
//                Log.e("tag","onAnimationEnd")
//
//            }
//
//            override fun onAnimationCancel(animation: Animator?) {
//
//                Log.e("tag","onAnimationCancel")
//
//            }
//
//            override fun onAnimationRepeat(animation: Animator?) {
//                Log.e("tag","onAnimationRepeat")
//
//            }
//
//        })

        mainActivityBinding?.tvService?.setOnClickListener{
               val myService = MyService()
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) {
            return
        }
        if (requestCode == REQUEST_CODE_FLUTTER) {
            if (data != null && data.extras != null) {
                //FlutterBoost 返回的数据 key 固定是 IFlutterViewContainer.RESULT_KEY ，value 为 MutableMap
                val resultDataMap: MutableMap<Any, Any> =
                    data.extras?.get(IFlutterViewContainer.RESULT_KEY) as MutableMap<Any, Any>
                val name = resultDataMap[RouterKey.Test.HasResultActivity.EXTRA_KEY_NAME].toString()
                val age = resultDataMap[RouterKey.Test.HasResultActivity.EXTRA_KEY_AGE] as Int
                mainActivityBinding?.tvResultData?.text =  String.format("Flutter 页面回调数据：姓名：$name，年龄：$age")
            }
        }
    }


     fun judegeRegx(source:String){

         val pattern = Pattern.compile("([0-9]|\\.)*")
         val matcher = pattern.matcher(source)

         Log.e("tag","matcher--->"+ matcher.matches())

     }

    internal class MyLengthFilter(
        /**
         * @return the maximum length enforced by this input filter
         */
        val max: Int, context: Context
    ) : InputFilter {
        private val context: Context
        override fun filter(
            source: CharSequence, start: Int, end: Int, dest: Spanned,
            dstart: Int, dend: Int
        ): CharSequence? {
            var keep: Int = max - (dest.length - (dend - dstart))
            return if (keep <= 0) {
                //这里，用来给用户提示
                Toast.makeText(context, "字数不能超过" + max, Toast.LENGTH_SHORT).show()
                ""
            } else if (keep >= end - start) {
                null // keep original
            } else {
                keep += start
                if (Character.isHighSurrogate(source[keep - 1])) {
                    --keep
                    if (keep == start) {
                        return ""
                    }
                }
                source.subSequence(start, keep)
            }
        }

        init {
            this.context = context
        }
    }

    override fun onBackPressed() {
        super.onBackPressed()
    }

    override fun onStart() {
        super.onStart()
        Log.e("tag","onStart")

    }

    override fun onResume() {
        super.onResume()
        Log.e("tag","onResume")

    }

    override fun onRestart() {
        super.onRestart()
        Log.e("tag","onRestart")

    }

    override fun onPause() {
        super.onPause()
        Log.e("tag","onPause")

    }

    override fun onStop() {
        super.onStop()
        Log.e("tag","onStop")

    }

    override fun onDestroy() {
        super.onDestroy()
        Log.e("tag","onDestroy")

    }

}